package com.hexb.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @Package : com.hexb.core.utils
 * @Author : hexb
 * @Date : 2018-08-26 17:42
 */
@Slf4j
public class ObjectUtils {

    /**
     * 发生异常时返回defaultValue
     */
    static public <T, R> R safeCall(Function<T, R> fun, T t, R defaultValue) {
        try {
            R r = fun.apply(t);
            return r;
        } catch (NullPointerException ex) {
            log.error(ex.getMessage());
        } catch (ArrayIndexOutOfBoundsException ex) {
            log.error(ex.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return defaultValue;
    }

    /**
     * 发生异常时返回defaultValue
     */
    static public <T> T safeCall(Supplier<T> fun, T defaultValue) {
        try {
            T r = fun.get();
            return r;
        } catch (NullPointerException ex) {
            log.error(ex.getMessage());
        } catch (ArrayIndexOutOfBoundsException ex) {
            log.error(ex.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return defaultValue;
    }

    /**
     * 无返回值
     */
    static public <T> void safeCall(Consumer<T> consumer, T param) {
        try {
            consumer.accept(param);
        } catch (NullPointerException ex) {
            log.error(ex.getMessage());
        } catch (ArrayIndexOutOfBoundsException ex) {
            log.error(ex.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }


    /**
     * 无返回值,无参数
     */
    static public void safeCall(Action action) {
        try {
            action.execute();
        } catch (NullPointerException ex) {
            log.error(ex.getMessage());
        } catch (ArrayIndexOutOfBoundsException ex) {
            log.error(ex.getMessage());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }


    /**
     * 列表转换为map
     *
     * @param list        源列表
     * @param keyProperty 用于做为map键的字段名
     */
    static public <T> Map<Object, T> list2map(List<T> list, String keyProperty) {
        return ObjectHelper.listToMap(list, keyProperty);
    }
}
